package com.lovemanai.test;

import java.util.Set;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.lovemanai.entity.Email;
import com.lovemanai.entity.Letter;
import com.lovemanai.entity.User;
import com.lovemanai.util.HibernateSessionFactory;

public class Demo1 {

	@Test
	public void test1() {
		Session s = HibernateSessionFactory.getSession();
		System.out.println(s);
		User user = (User) s.get(User.class,4);
		System.out.println(user.getName());
		Set<Email> emails = user.getEmails();
		for (Email email : emails) {
			System.out.println(email.getAddr());
		}
		s.close();
	}
	
	/**
	 * 添加letter，级联添加email,user
	 */
	@Test
	public void test2() {
		Session s = HibernateSessionFactory.getSession();
		User user = new User("黄月英");
		Email email = new Email("huangyueying@hotmail.com");
		Letter letter = new Letter("这是黄月英的一封邮件");
		email.getLetters().add(letter);//设置关系
		letter.setEmail(email);
		email.setUser(user);
		user.getEmails().add(email);//设置关系
	
		Transaction tx = s.beginTransaction();
		
		s.save(letter);
		
		tx.commit();
		s.close();
	}
	
	/**
	 * 添加User，级联添加Email，Letter
	 */
	@Test
	public void test3() {
		Session s = HibernateSessionFactory.getSession();
		Letter letter = new Letter("这是甄姬的邮件");
		Email email = new Email("zhenji@163.com");
		User user = new User("甄姬");
		//设置关系
		user.getEmails().add(email);
		email.getLetters().add(letter);
		email.setUser(user);
		letter.setEmail(email);
	
		Transaction tx = s.beginTransaction();
		
		s.save(user);
		
		tx.commit();
		s.close();
	}
	
	/**
	 * 修改
	 */
	@Test
	public void test4() {
		Session s = HibernateSessionFactory.getSession();
		User user1 = (User) s.get(User.class, 4);
		User user2 = (User) s.get(User.class, 5);
		Set<Email> emails = user1.getEmails();
		for (Email email : emails) {
			user1.getEmails().remove(email);
			user2.getEmails().add(email);
			email.setUser(user2);
		}
		
		Transaction tx = s.beginTransaction();
		
		s.update(user1);
		s.update(user2);
		
		tx.commit();
		
		s.close();
	}
	
	@Test
	public void test5() {
		Session s = HibernateSessionFactory.getSession();
		User user = (User) s.get(User.class, 6);
		
		Transaction tx = s.beginTransaction();
		
		s.delete(user);
		
		tx.commit();
		
	}
	
	
	public static void main(String[] args) {
		new Demo1().test4();
	}
}